package com.zhongge.util;

import java.sql.*;

import java.util.ResourceBundle;

/**
 * @ClassName DbUtils
 * @Description TODO
 * @Author zhongge
 * @Version 1.0
 */
public class DbUtils {
    private static  String driver;
    private static  String url;
    private static  String password;
    private static  String username;

    private DbUtils() {
    }

    static {
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        driver = bundle.getString("driver");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");

        //注册驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return 连接
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    public static void close(ResultSet resultSet,
                             PreparedStatement preparedStatement,
                             Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet re = null;

        try {
            //获取连接
            connection = DbUtils.getConnection();

            //sql
            String sql = "select * from users";

            //预处理对象
            ps = connection.prepareStatement(sql);

            //获取结果集对象
            re = ps.executeQuery();

            while (re.next()) {
                int id = re.getInt(1);
                String  username = re.getString(2);
                String email = re.getString(3);
                String password = re.getString(4);
                System.out.println(id + username + email + password);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.close(re, ps, connection);
        }
    }
}
